﻿Imports System.Text
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Net
Imports System.ComponentModel.Composition

<Export(GetType(PluginInterfaces.IClicknLoadPlugin))>
Public Class CnL_tinyupload
    Implements PluginInterfaces.IClicknLoadPlugin


#Region "Interne Plugin Funktionen"

    Private Function GetResponse(ByVal url As String) As String

        Dim _cookie_container As New CookieContainer
        Dim _http_webrequest As HttpWebRequest
        Dim _http_response As HttpWebResponse
        Dim _rt As String

        If Not url.StartsWith("http://") Then
            url = "http://" & url
        End If

        _http_webrequest = CType(HttpWebRequest.Create(url), HttpWebRequest)
        _http_webrequest.CookieContainer = _cookie_container
        _http_response = CType(_http_webrequest.GetResponse(), HttpWebResponse)

        _rt = New StreamReader(_http_response.GetResponseStream()).ReadToEnd()

        _http_response.Close()

        Return _rt

    End Function

    Private Sub ReadWriteStream(readStream As Stream, writeStream As Stream)
        Dim Length As Integer = 256
        Dim buffer As [Byte]() = New [Byte](Length - 1) {}
        Dim bytesRead As Integer = readStream.Read(buffer, 0, Length)
        ' write the required bytes
        While bytesRead > 0
            writeStream.Write(buffer, 0, bytesRead)
            bytesRead = readStream.Read(buffer, 0, Length)
        End While
        readStream.Close()
        writeStream.Close()
    End Sub

    Private Function GetFileID(ByVal _web_response As String) As String

        Dim _rt As String = ""
        Dim sourcestring As String = _web_response
        Dim re As Regex = New Regex("=[0-9]+&")
        Dim mc As MatchCollection = re.Matches(sourcestring)
        Dim mIdx As Integer = 0

        Dim m As Match = mc(0)

            For groupIdx As Integer = 0 To m.Groups.Count - 1
                If Not String.IsNullOrEmpty(m.Value.ToString) Then
                    _rt = m.Value.ToString.Replace("&", "")
                    _rt = _rt.Replace("=", "")
                End If
            Next

        Return _rt

    End Function

    Private Function GetHostID(ByVal _web_response As String) As String

        Dim _rt As String = ""
        Dim sourcestring As String = _web_response
        Dim re As Regex = New Regex("((?:[a-z][a-z\.\d\-]+)\.(?:[a-z][a-z\-]+))(?![\w\.])")
        Dim mc As MatchCollection = re.Matches(sourcestring)
        Dim mIdx As Integer = 0

        Dim m As Match = mc(0)

            For groupIdx As Integer = 0 To m.Groups.Count - 1
                If Not String.IsNullOrEmpty(m.Value.ToString) Then
                    _rt = m.Value.ToString
                End If
            Next

        Return _rt

    End Function


    Private Function GetTID(ByVal _web_response As String) As String


        Dim _rt As String = ""
        Dim sourcestring As String = _web_response
        Dim re As Regex = New Regex("[0-9]{25}")
        Dim mc As MatchCollection = re.Matches(sourcestring)
        Dim mIdx As Integer = 0

        For Each m As Match In mc
            For groupIdx As Integer = 0 To m.Groups.Count - 1
                If Not String.IsNullOrEmpty(m.Value.ToString) Then
                    _rt = m.Value.ToString
                End If
            Next
            mIdx = mIdx + 1
        Next

        Return _rt

    End Function


#End Region

    Public Function DownloadSFDL(_url As String) As String Implements PluginInterfaces.IClicknLoadPlugin.DownloadSFDL

        Dim _cookie_container As New CookieContainer
        Dim _http_webrequest As HttpWebRequest
        Dim _http_response As HttpWebResponse
        Dim _post As String = String.Empty
        Dim _web_request_url As String = String.Empty
        Dim _saveTo As String = String.Empty
        Dim _rt As String = String.Empty
        Dim _tmp_response As String = String.Empty

        Dim _fileid As String = String.Empty
        Dim _tid As String = String.Empty
        Dim _hostid As String = String.Empty

        Try


            Debug.WriteLine("RAW Link:" & _url)

            _tmp_response = GetResponse(_url)

            _fileid = GetFileID(_tmp_response)
            _tid = GetTID(_tmp_response)
            _hostid = GetHostID(_url)

            Debug.WriteLine("FileID: {0}", _fileid)
            Debug.WriteLine("TID: {0}", _tid)
            Debug.WriteLine("HostID: {0}", _hostid)

            _web_request_url = String.Format("http://{0}/download.php?file_id={1}&t={2}", _hostid, _fileid, _tid)

            Debug.WriteLine("Web Request URL=" & _web_request_url)

            _http_webrequest = CType(HttpWebRequest.Create(_web_request_url), HttpWebRequest)

            With _http_webrequest

                .Method = "GET"
                .CookieContainer = _cookie_container
                .UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0"
                .ContentType = "application/x-www-form-urlencoded"

            End With

            _http_response = CType(_http_webrequest.GetResponse(), HttpWebResponse)

            _saveTo = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Temp, IO.Path.GetRandomFileName)

            Dim writeStream As New FileStream(_saveTo, FileMode.Create, FileAccess.Write)

            ' write to the stream
            ReadWriteStream(_http_response.GetResponseStream(), writeStream)

            _http_response.Close()

            _rt = _saveTo

        Catch ex As Exception
            Debug.WriteLine("Error: {0}", ex.Message)
            _rt = ""
        End Try

        Return _rt

    End Function

    Public Function SupportedHosts() As List(Of String) Implements PluginInterfaces.IClicknLoadPlugin.SupportedHosts

        Dim _rt_list As New List(Of String)

        _rt_list.Add("tinyupload.com")

        Return _rt_list

    End Function

    Public Function URLSupported(_url As String) As Boolean Implements PluginInterfaces.IClicknLoadPlugin.URLSupported

        If _url.Contains("tinyupload.com") Then
            Return True
        Else
            Return False
        End If

    End Function

    Public Function GetAuthor() As String Implements PluginInterfaces.ISFDLLoaderPlugin.GetAuthor
        Return "Seji"
    End Function

    Public Function GetName() As String Implements PluginInterfaces.ISFDLLoaderPlugin.GetName
        Return "ClicknLoad Plugin tinyupload.com"
    End Function

    Public Function GetSettingsTabName() As String Implements PluginInterfaces.ISFDLLoaderPlugin.GetSettingsTabName
        Throw New NotImplementedException("Keine Einstellungen vorhanden")
    End Function

    Public Function GetVersion() As String Implements PluginInterfaces.ISFDLLoaderPlugin.GetVersion
        Return "0.1"
    End Function

    Public Function HasSettings() As Boolean Implements PluginInterfaces.ISFDLLoaderPlugin.HasSettings
        Return False
    End Function

    Public Sub Initialize() Implements PluginInterfaces.ISFDLLoaderPlugin.Initialize
        'Nothing to do
    End Sub

    Public Sub SaveSettings() Implements PluginInterfaces.ISFDLLoaderPlugin.SaveSettings
        Throw New NotImplementedException("Keine Einstellungen vorhanden")
    End Sub

    Public Function GetSettingsTab() As System.Windows.Forms.UserControl Implements PluginInterfaces.ISFDLLoaderPlugin.GetSettingsTab
        Throw New NotImplementedException("Keine Einstellungen vorhanden")
    End Function
End Class
